﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.IO;
using System.Net;
using Model.ZSJL.com.Net;
using System.Text.RegularExpressions;

namespace Service.ZSJL.Com.Net
{
    public class ZTSMSService : ISmsService
    {
        //平台  最土网，没有回复 功能 。

        // http://notice.zuitu.com/sms?user=USERNAME&pass=PASSWORD&phones=PHONES&content=CONTENT

        //USERNAME：在本短信平台注册的用户名
        //PASSWORD：平台登录密码MD5后的值
        //PHONES：目标手机号码，多个手机号码使用半角逗号分隔，最多300个
        //CONTENT：发送内容，编码建议采用UTF-8
        //返回 '+OK' 视为发送成功，其他内容为错误提示内容

        private SmsConfig _smsConfig;

        public SmsConfig SmsConfig
        {
            get { return _smsConfig; }
            set { _smsConfig = value; }
        }

        private string _returnurlname;
        /// <summary>
        /// 设置路径的名称
        /// </summary>
        public string returnurlname
        {
            get { return _returnurlname; }
            set { _returnurlname = value; }
        }



        private string _returntypes;
        /// <summary>
        /// 设置返回信息数量的类型"Left"是剩余信息数，"Used"是使用了的信息数
        /// </summary>
        public string returntypes
        {
            get { return _returntypes; }
            set { _returntypes = value; }
        }
        public ZTSMSService()
        {
            //初始化默认配置
            Init();
        }

        /// <summary>
        /// 带参数
        /// </summary>
        /// <param name="smsConfig"></param>
        public ZTSMSService(SmsConfig smsConfig)
        {
            this._smsConfig = smsConfig;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            this.SmsConfig = new SmsConfig();

            SmsConfig.Password = "94C9F245C24843787770BF93D1208734";
            SmsConfig.SmsAPIUrl = "http://notice.zuitu.com/sms";
            SmsConfig.UserId = "djdnmq";
        }



        private string HttpGet(string action, string Datas, HttpAccessType ac)
        {
            string ReUrl = "";
            string line = "";
            string param = "?user=" + SmsConfig.UserId + "&pass=" + SmsConfig.Password + Datas;
            byte[] bs = Encoding.ASCII.GetBytes(param);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(SmsConfig.SmsAPIUrl + param);
            req.Method = ac.ToString();
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; .NET CLR 1.1.4322)";
            req.Proxy = null;       //绕过代理,快速发送

            WebResponse wr = req.GetResponse();
            Stream strm = wr.GetResponseStream();
            StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);

            while ((line = sr.ReadLine()) != null)
            {
                ReUrl += line;
            }
            strm.Close();
            return ReUrl;
        }

        /// <summary>
        /// 发送短信内容
        /// </summary>
        /// <param name="smsModel"></param>
        /// <returns></returns>
        public string SendSmsAPI(SmsModel smsModel)
        {
            if (string.IsNullOrEmpty(smsModel.PhoneNo) || smsModel.PhoneNo.Length < 11)
                throw new Exception("nonum电话号码为空！");
            string Datas = "";

            Datas += "&" + "phones" + "=" + smsModel.PhoneNo;
            Datas += "&" + "content" + "=" + HttpUtility.UrlEncode(smsModel.Content, Encoding.GetEncoding("UTF-8"));

            return HttpGet("SendSms", Datas, HttpAccessType.GET);
        }



        #region ISMSService Members

        public List<SmsModel> GetReplySMSTable()
        {
            throw new NotImplementedException();
        }

        public List<SmsModel> GetReplySMSTable(DateTime time)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="smsContent"></param>
        /// <returns></returns>
        public bool SendSms(SmsModel smsContent)
        {
            string result = SendSmsAPI(smsContent);

            //成功返回？
            if (result.IndexOf("+OK") > -1)
                return true;
            else
                throw new Exception(result);
        }



        //public int CheckSumSms()
        //{
        //    throw new Exception(result);
        //    string Sumsms = "http://notice.zuitu.com/user/" +SmsConfig.UserId;
        //    return PostRequest(Sumsms, returntypes, "");

        //}

        //public int CheckSumSms(string type)
        //{
        //    string Sumsms = "http://notice.zuitu.com/user/" + SmsConfig.UserId;
        //    return PostRequest(Sumsms, returntypes, "");

        //}
        private string StripHtml(string strHtml, string returntype)//去除html标签并获取参数
        {
            Regex objRegExp = new Regex("<(.|\n)+?>");
            string strOutput = objRegExp.Replace(strHtml, "");
            strOutput = strOutput.Replace("<", "&lt;");
            strOutput = strOutput.Replace(">", "&gt;");
            Regex r = new Regex(@"\s+");
            strOutput = r.Replace(strOutput, " ");
            strOutput = strOutput.Trim();
            Regex enelt = new Regex("[a-zA-Z]");
            strOutput = enelt.Replace(strOutput, "");
            string[] str = strOutput.Split(':');
            if (returntype == "Left")
                strOutput = str[1];
            else if (returntype == "Used")
                strOutput = str[1];
            else
                strOutput = "0";

            return strOutput;
        }
        public int PostRequest(string url, string returntype, string postData)//远程抓取数据内容
        {
            //postData获取url地址中的一个参数
            //制定编码格式
            var encoding = Encoding.GetEncoding("gb2312");
            //url的设置
            var request = (HttpWebRequest)WebRequest.Create(url);
            //设置请求的方式
            request.Method = "POST";
            //设置Content-Type 的值
            request.ContentType = "application/x-www-form-urlencoded";

            var data = encoding.GetBytes(postData);
            request.ContentLength = data.Length;
            var outStream = request.GetRequestStream();
            outStream.Write(data, 0, data.Length);
            outStream.Close();
            var response = (HttpWebResponse)request.GetResponse();
            var srContent = new System.IO.StreamReader(response.GetResponseStream(), encoding);
            //获取抓取下来的页面内容
            var strPage = srContent.ReadToEnd();
            response.Close();
            srContent.Close();
            strPage = StripHtml(strPage, returntype);

            return Convert.ToInt32(strPage);
        }
        #endregion


        public int CheckSumSms()
        {

            string Sumsms = "http://notice.zuitu.com/user/" + SmsConfig.UserId;
            return PostRequest(Sumsms, "Left", "");
        }

        public int CheckUseSms()
        {
            string Sumsms = "http://notice.zuitu.com/user/" + SmsConfig.UserId;
            return PostRequest(Sumsms, "Used", "");
        }
    }
}
